package com.hk.Mgr.web.controller.kyc;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hk.Mgr.web.message.StatusCode;
import com.hk.Mgr.web.message.kyc.SuggestionReq;
import com.hk.Mgr.web.message.kyc.SuggestionRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.Constant;
import com.hk.commons.DateUtil;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.Suggestion;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.yingmi.YingmiApiUtils;
import com.hk.service.IOrganization;
import com.hk.service.kyc.ISuggestion;
import com.hk.service.sys.ISysUser;

@Controller
@RequestMapping(value = BaseCtrl.MgrRootPath + "/suggestionCtrl")
public class SuggestionCtrl extends BaseCtrl {

	@Autowired
	private ISuggestion suggestionService;

	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IOrganization orgService;

	private Logger logger = LoggerFactory.getLogger(SuggestionCtrl.class);

	@Autowired
	public YingmiApiUtils utils;

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> update(@RequestBody SuggestionReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();

		if(req == null || req.getResponder() == null||req.getUserId()==null){
			logger.error("更改意见建议失败");
			resp.setMsg("用户未登录,不允许修改");
			resp.setResultCode(StatusCode.PARAM_ERROR.key());
		}


		if ( req.getResponder() == null || !sysUserService.existById(req.getResponder())) {
			logger.error("更改意见建议失败");
			resp.setMsg("用户未登录,不允许修改");
			resp.setResultCode(StatusCode.USER_NOTLOGIN.key());
		} else {
			Suggestion sug = suggestionService.findById(req.getId());
			if (req == null || req.getId() == null) {
				resp.setResultCode(StatusCode.PARAM_ERROR.key());
				resp.setMsg("参数不对：id is null！");
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());
				return resp;
			} else {
				if (StringUtils.isNoneEmpty(req.getSuggestionAnswer())) {
					sug.setSuggestionAnswer(req.getSuggestionAnswer());
					sug.setStatus(Constant.SUGGESTION_RESPONSE);
					sug.setResponder(req.getResponder());
					sug.setUpdTime(System.currentTimeMillis());
				}
			}
			sug.setUpdTime(System.currentTimeMillis());
			suggestionService.update(sug);

			resp.setResult(true);
			resp.setResultCode(StatusCode.SUCCESS.key());
		}

		return resp;
	}

	/**
	 * 获得所有意见建议
	 * 
	 * @author jeff
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<SuggestionRes>> list(
			@RequestBody SuggestionReq req) {
		ResponseBase<List<SuggestionRes>> resp = new ResponseBase<>();
		if (req.getUserId() == null
				|| !sysUserService.existById(req.getUserId())) {
			logger.error("用户未登录,获取意见列表失败");
			resp.setMsg("用户未登录,获取意见列表失败");
			resp.setResultCode(StatusCode.USER_NOTLOGIN.key());
		} else {

			List<SuggestionRes> suggestionReslist = new ArrayList<>();

			HqlFilter hqlFilter = new HqlFilter();
			
			 
			hqlFilter.addSort("cts");
			hqlFilter.addOrder("desc");
			
			List<Suggestion> list = null;
			
			if(req.getPageSize() > 50){
				
				list = suggestionService.findByFilter(hqlFilter);
				SuggestionRes suggestionRes = new SuggestionRes();
				suggestionReslist.add(suggestionRes);
				resp.setSize(list.size());
				resp.setResult(suggestionReslist);
				resp.setResultCode(StatusCode.SUCCESS.key());
				return resp;
			}
			
			list = suggestionService.findByFilter(hqlFilter,
					req.getCurPage(), req.getPageSize());
			try {
				for (Suggestion sug : list) {
					SuggestionRes suggestionRes = new SuggestionRes();

					suggestionRes.setId(sug.getId().toString());
					suggestionRes.setSuggestion(sug.getSuggestion());
					suggestionRes
							.setSuggestionAnswer(sug.getSuggestionAnswer());
					suggestionRes.setChannel(sug.getChannel());

					DateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd hh:mm:ss");// 设定格式

					if (sug.getCts() != null) {
						suggestionRes.setCtsStr(DateUtil.longToLongDate(sug.getCts()));
						suggestionRes.setCts(sug.getCts().toString());
					}

					if (sug.getUpdTime() != null) {
						Timestamp updTime = new Timestamp(sug.getUpdTime());
						suggestionRes.setUpdTimeStr(dateFormat.format(updTime));
						suggestionRes.setUpdTime(sug.getUpdTime().toString());
					}
					// 添加提建议者的信息
					SysUser user = new SysUser();
					Long UserId = Long.valueOf(sug.getUserId());
					user = sysUserService.findById(UserId);
					suggestionRes.setUserId(user.getId().toString());
					suggestionRes.setUserName(user.getRealName());
					suggestionRes.setUserPhone(user.getName());
					// 添加回复者的信息
					Long responderId = sug.getResponder();
					if (responderId != null
							&& sysUserService.existById(responderId)) {
						SysUser responder = sysUserService
								.findById(responderId);
						suggestionRes
								.setResponder(responder.getId().toString());
						suggestionRes.setResponderName(responder.getName());

						Integer orgId = responder.getOrgId();
						if (orgId != null
								&& orgService.findById(orgId) != null) {
							Organization org = orgService.findById(orgId);
							if(org != null){
								suggestionRes.setResponderDepName(orgService.getDepNameById(org.getId()));
							}
						}
					}

					if (sug.getStatus() == Constant.SUGGESTION_NO_RESPONSE) {
						suggestionRes.setStatus("未回复");
					} else {
						suggestionRes.setStatus("已回复");
					}

					suggestionReslist.add(suggestionRes);
				}

				resp.setSize(suggestionReslist.size());
				resp.setResult(suggestionReslist);
				resp.setResultCode(StatusCode.SUCCESS.key());

			} catch (Exception e) {
				logger.error("保存意见建议失败");
				resp.setMsg("保存意见建议失败，请重试");
				resp.setResultCode(StatusCode.EXCEPTION.key());
			}

		}
		return resp;
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<Boolean> save(@RequestBody SuggestionReq req) {
		ResponseBase<Boolean> resp = new ResponseBase<>();
		if (req.getUserId() == null
				|| !sysUserService.existById(req.getUserId())) {
			logger.error("保存意见建议失败");
			resp.setMsg("用户未登录,建议保存失败");
			resp.setResultCode(StatusCode.USER_NOTLOGIN.key());
		} else {

			Suggestion sug = new Suggestion();
			try {
				ReqToModelHelper.copyReqValueToModel(req, sug);
				sug.setStatus(Constant.SUGGESTION_NO_RESPONSE);
				suggestionService.add(sug);
				resp.setResult(true);
				resp.setResultCode(StatusCode.SUCCESS.key());

			} catch (Exception e) {
				logger.error("保存意见建议失败");
				resp.setMsg("保存意见建议失败，请重试");
				resp.setResultCode(StatusCode.EXCEPTION.key());
			}
		}
		return resp;
	}
}
